<?php

// An example of using php-webdriver.
namespace Facebook\WebDriver;

use Facebook\WebDriver\Remote\DesiredCapabilities;
use Facebook\WebDriver\Remote\RemoteWebDriver;

require_once('vendor/autoload.php');

// start Firefox with 5 second timeout
$host = 'http://localhost:4444/wd/hub'; // this is the default
$capabilities = DesiredCapabilities::chrome();
$driver = RemoteWebDriver::create($host, $capabilities, 5000);
$size = new WebDriverDimension(1280, 900);
$driver->manage()->window()->setSize($size);
$driver->get('http://www.jd.com');
// adding cookie
$driver->manage()->deleteAllCookies();
$driver->manage()->addCookie(array(
    'name' => 'cookie_name',
    'value' => 'cookie_value',
));
$cookies = $driver->manage()->getCookies();
//print_r($cookies);
// print the title of the current page
echo "The title is '" . $driver->getTitle() . "'\n";
// print the URI of the current page
echo "The current URI is '" . $driver->getCurrentURL() . "'\n";

//在商品搜索框输入商品自动搜索
$input = $driver->findElement(
    WebDriverBy::id('key')
);
$input->sendKeys('iPhone 8');

//查找到搜索按钮
$button = $input->findElement(
    WebDriverBy::xpath("../button[1]")
);
$button->click();

// wait at most 10 seconds until at least one result is shown
try {
    $driver->wait(3)->until(
        WebDriverExpectedCondition::presenceOfAllElementsLocatedBy(
            WebDriverBy::className('gl-warp')
        )
    );

$links = $driver->findElements(WebDriverBy::cssSelector(".gl-i-wrap > .p-img > a"));
$aTags = [];
foreach($links as $value) {
    array_push($aTags, array(
        'href' => $value->getAttribute('href'),
        'title' => $value->getAttribute("title")
    ));
}

    print_r($aTags);

} catch (\Exception $e) {

}
//注入 js 代码
$driver->executeScript("document.body.scrollTop = 1000; alert(arguments[0])", ["fuck"]);
sleep(2);
//$driver->takeScreenshot("test.png");

$driver->getMouse()->click();
$driver->getKeyboard()->pressKey(WebDriverKeys::SHIFT);
$driver->getKeyboard()->releaseKey(WebDriverKeys::SHIFT);
// close the browser
$driver->quit();
